package cn.itcast.bos.web.action.base;

import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import cn.itcast.bos.constant.Constants;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@Controller
@Namespace("/")
@ParentPackage("struts-default")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CustomerAction extends BaseAction<Customer> {

	private String checkCode;

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	private String mailCode;

	public void setMailCode(String mailCode) {
		this.mailCode = mailCode;
	}

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jsmTemplate;

	// 保存用户
	@Action(value = "signup_addCustomer", results = {
			@Result(name = "success", type = "redirect", location = "./signup-success.html"),
			@Result(name = "input", type = "redirect", location = "./signup.html") })
	public String addCustomer() {
		// 获取session中的手机验证码
		String random = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (random == null || !random.equals(checkCode)) {
			System.out.println("验证码不匹配");
			return INPUT;
		} else {
			// 保存用户
			WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/addCustomer")
					.type(MediaType.APPLICATION_JSON).post(model);
			System.out.println("添加用户成功");
		}
		// 发送验证邮件
		// 生成32位随机激活码
		String mailRandom = RandomStringUtils.randomNumeric(32);
		// 激活码保存到redis中
		redisTemplate.opsForValue().set(model.getTelephone(), mailRandom, 24, TimeUnit.HOURS);
		final String content1 = "尊敬的用户,您好.请点击以下的连接,激活您的邮箱.<a href=";
		final String content3 = "?telephone=" + model.getTelephone() + "&mailCode=" + mailRandom + ">点击此处以激活</a>";
		final String subject = "速运快递激活邮件";
		// activeMQ 发送消息
		jsmTemplate.send("bos_mail", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("content1", content1);
				mapMessage.setString("content3", content3);
				mapMessage.setString("subject", subject);
				mapMessage.setString("mail", model.getEmail());
				return mapMessage;
			}
		});
		// 发送邮件,主题,内容,收件邮箱地址
		//
		System.out.println("激活邮件已发送");
		return SUCCESS;
	}

	// 校验手机验证码
	@Action(value = "signup_checkCode")
	public void checkCode() {
		// 生成4位随机验证码
		String random = RandomStringUtils.randomNumeric(4);
		System.out.println("验证码:" + random);
		final String content = "您好,您的验证码为:" + random;
		// 保存验证码到session
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), random);
		// activeMQ 发送消息
		jsmTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("content", content);
				return mapMessage;
			}
		});
		System.out.println("短信发送成功");
	}

	// 激活邮箱
	@Action(value = "signup_activeMail")
	public void activeMail() throws Exception {
		// 处理响应到页面乱码
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		// 获取redis中的激活码
		String mailRandom = redisTemplate.opsForValue().get(model.getTelephone());
		// 判断激活码是否匹配
		if (mailRandom == null || !mailRandom.equals(mailCode)) {
			ServletActionContext.getResponse().getWriter().println("验证码错误或已过期");
		} else {
			// 查询用户是否激活
			Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/findByTelephone")
					.query("telephone", model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType() == null || customer.getType() != 1) {
				// 修改激活状态
				WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/updateType")
						.query("telephone", model.getTelephone()).type(MediaType.APPLICATION_JSON).put(null);
				System.out.println("邮箱激活成功");
				ServletActionContext.getResponse().getWriter().println("邮箱激活成功");
			} else {
				ServletActionContext.getResponse().getWriter().println("账户已经被激活");
			}
			// 激活后清空激活码
			redisTemplate.delete(model.getTelephone());
		}
	}

	@Action(value = "customer_login", results = {
			@Result(name = "success", type = "redirect", location = "./index.html"),
			@Result(name = "login", type = "redirect", location = "./login.html") })
	public String login() {
		String telephone = model.getTelephone();
		String password = model.getPassword();
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/loginCheck")
				.query("telephone", telephone).query("password", password).accept(MediaType.APPLICATION_JSON)
				.get(Customer.class);
		if (customer != null) {
			ServletActionContext.getRequest().getSession().setAttribute("existCustomer", customer);
			return SUCCESS;
		} else {
			return LOGIN;
		}
	}
}
